<template>
  <div>
    <el-upload
      action="1"
      list-type="picture-card"
      :multiple="true"
      :limit="limit"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="onexceed"
      :file-list="fileimg"
      :http-request="httpRequest"
      id="uploderimg"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
    <div slot="tip" class="el-upload__tip" id="tip">图片不能超过2M 上传图片推荐为400：400</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      headers: {},
      fileLists: [],
      fileimg: []
    };
  },
  props: ["limit"],
  mounted() {
    let header = sessionStorage.getItem("user");
    let head = JSON.parse(header);
    this.headers = {
      "Content-Type": "application/json;charset=UTF-8",
      "X-Access-Token": head.token,
      "X-Access-Uid": head.id
    };
  },
  methods: {
    handleRemove(file) {
      //删除元素

      let fileid = "";
      if (this.$route.query.id) {
        this.fileimg.map((item, index) => {
          console.log(item, index, file);
          if (item === file) {
            fileid = index;
          }
        });
        console.log(fileid);
        this.fileimg.splice(fileid, 1);
        this.fileLists.splice(fileid, 1);
        this.$emit("getfileid", fileid);
      } else {
        this.fileLists.map((item, index) => {
          if (item === file) {
            fileid = index;
          }
        });
        this.fileLists.splice(fileid, 1);
        this.$emit("getfileid", fileid);
      }
    },
    cliear() {
      this.fileLists = [];
      this.fileimg = [];
    },
    editimg(arr) {
      //修改图片
      for (let index = 0; index < arr.length; index++) {
        if (arr[index]) {
          this.fileimg.push({ name: "轮播图", url: arr[index] });
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    httpRequest(file) {
      this.fileLists.push(file.file);
      let formData = new FormData();
      formData.append("image", file.file);
      this.$store
        .dispatch("upimg", formData)
        .then(result => {
          if (!result.code) {
            this.dialogImageUrl = result.data.path;
            console.log(result.data.data);
            this.$emit("getpath", result.data.path);
            this.$message({
              type: "success",
              message: "上传成功",
              duration: 1000
            });
          }
        })
        .catch(() => {
          //   console.log(err);
        });
    },
    onexceed() {
      this.$message.error("最多上传4张轮播");
    }
  }
};
</script>